(function(){
	/**
	 * 自增ID,用于生成全局回调函数名称和script element id
	 */
	var sid = 0;
	
	var history = {};
	
	/**
	 * 发送jsonp请求
	 * @param {String} url 请求url
	 * @param {Function} cb 回调函数
	 */
	function do_jsonp(url, cb){
		var callback 	= '_do_json' + sid,
			scriptid 	= '_do_json_scr' + sid,
			head 		= document.getElementsByTagName('head')[0],
			script		= document.createElement('script');
		script.id = scriptid;
		history[callback] = true;
		window[callback] = function(){
			if (history[callback]){
				//调用回调函数
				cb.apply(cb, arguments);				
			}
			history[callback] = null;
			//防止内存泄露 参见 http://neil.fraser.name/news/2009/07/27/
			script.parentNode.removeChild(script);
			/*会造成IE6下innerHTML属性设置错误问题,暂不使用
			for (var prop in script){
				try {
					script[prop] = null;
					delete script[prop];
				}catch(e){}
			}
			*/	
			window[callback] = function(){};
		};		
		++sid;
		if (/\{cb\}/i.test(url)){
			//替换callback名称
			url.replace(/\{cb\}/i, callback)
		}
		else{
			url += ((url.indexOf('?') != -1) ? '&' : '?') + 'callback=' + callback;
		}
		script.src = url;
		script.type = 'text/javascript';
		head.appendChild(script);
	}

	/**
	 * 封装yql请求
	 * @param {Object} reqUrl 需要YQL抓取的网页
	 * @param {Object} cb 回调函数
	 * @param {Object} options 选项
	 *  {
	 *  	format : string[json|xml],
	 *  	xpath  : string XPATH表达式
	 *  }
	 */
	function yql_request(reqUrl, cb, options){
		options = (typeof options == 'object') ? options : {};
		//默认格式JSON
		options.format = options.format ? options.format : 'json';
		var query = ['select * from html where url="' , reqUrl , '"'].join('');
		if (options.xpath){
			query += ' and xpath="' + options.xpath + '"';
		}
		var url = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(query) + '&format=' + options.format;
		do_jsonp(url, cb)
	}
	
	/**
	 * 发送yql请求,返回数据将xml转化为json
	 * @param {Object} reqUrl
	 * @param {Object} xpath
	 * @param {Object} cb
	 */
	function yql_req_json(reqUrl, xpath, cb){
		if(typeof xpath == 'function'){
			cb = xpath;
			xpath = null;
		}
		yql_request(reqUrl, cb, {'xpath':xpath, 'format':'json'});
	}
	
	/**
	 * 发送yql请求,返回数据将xml转化为string
	 * @param {Object} reqUrl
	 * @param {Object} xpath
	 * @param {Object} cb
	 */
	function yql_req_html(reqUrl, xpath, cb){
		if(typeof xpath == 'function'){
			cb = xpath;
			xpath = null;
		}		
		yql_request(reqUrl, cb, {'xpath':xpath, 'format':'xml'});
	}
	
	window.yql_req_json = yql_req_json;
	window.yql_req_html = yql_req_html;
})();

(function(){
/**
 * embedHelper
 * Copyright (c) 2009 James Padolsey
 * -------------------------------------------------------
 * Dual licensed under the MIT and GPL licenses.
 *    - http://www.opensource.org/licenses/mit-license.php
 *    - http://www.gnu.org/copyleft/gpl.html
 * -------------------------------------------------------
 * Version: 0.1
 */

var embedHelper = (function(){
    
    var SCRIPT = (function(){
        var domScripts = document.getElementsByTagName('script');
        return domScripts[ domScripts.length - 1 ];
    })();
    
    return {
        getConfig: function(defaults) {
            
            /* getConfig() will return the JSON config within
               the SCRIPT element - it can also merge this
               with any defaults specified */
            
            var inner = SCRIPT.innerHTML,
                config = {},
                args = Array.prototype.slice.call(arguments);
                
            try {
                config = (new Function('return ' + inner.replace(/\/\/(.*?)$/mg, '').replace(/\n|\r/g, '')))();
            } catch(e) { /* Invalid config */ }
            
            args.push(config);
            
            return this.merge.apply(this, args);
        
        },
        merge: function(target, source) {
            
            /* Merges two (or more) objects,
               giving the last one precedence */
            
            if ( typeof target !== 'object' ) { target = {}; }
            
            for (var property in source) {
                
                if ( !source.hasOwnProperty || source.hasOwnProperty(property) ) {
                    
                    var sourceProperty = source[ property ];
                    
                    if ( typeof sourceProperty === 'object' ) {
                        target[ property ] = this.merge( target[ property ], sourceProperty );
                        continue;
                    }
                    
                    target[ property ] = sourceProperty;
                    
                }
                
            }
            
            for (var a = 2, l = arguments.length; a < l; a++) {
                this.merge(target, arguments[a]);
            }
            
            return target;
        },
        getQueryParams: function() {
            
            /* Retrieves any query parameters used in the 'src'
               attribute of the SCRIPT */
            
            var src = SCRIPT.src,
                queryParts,
                qIndex,
                qSplit,
                params = {},
                args = Array.prototype.slice.call(arguments);
                
            if (src.indexOf('?') > -1) {
                
                queryParts = src.split('?')[1].split('&');
                qIndex = queryParts.length;
                
                while (qIndex--) {
                    qSplit = queryParts[qIndex].split('=');
                    params[ qSplit[0] ] = qSplit[1];
                }
                
            }
            
            args.push(params);
            
            return this.merge.apply(this, args);
            
        },
        insert: function(item){
            if (item.nodeName && !item.length) {
                return SCRIPT.parentNode.insertBefore( item, SCRIPT );
            }
            if (typeof item === 'string') {
                var temp = document.createElement('div');
                temp.innerHTML = item;
                item = temp.childNodes;
            }
            for (var i = 0, l = item.length || 0; i < l; ++i) {
                this.insert(item[i]);
            }
            return this;
        },
        scriptRef: SCRIPT
    };
    
})(); 
	
	var options = embedHelper.getConfig({
		'username' 	: 'thunderbean',
		'count'		: 5,
		'container' : {
			'id'		: 'itweet_widget',
			'tagname' 	: 'div',
			'classname' : 'itweet_widget_container',
			'html' 		: '{|$lines|}'
			
		},
		'lineTpl'	: '<p>{|$status|}</p>'
	});
	
	var con 		= document.createElement(options.container.tagname);
	con.id 			= options.container.id;
	con.className 	= options.container.classname;
	embedHelper.insert(con);		
	
	function afterShow(){
		var userLinks = con.getElementsByTagName('a'),
			len = userLinks.length,
			tmpLink = null;
	}
	
	function showTweets(r){
		if (r.error){
			con.innerHTML = r.error.description;
			return;
		}
		var ds   = r.results,
			d    = null,
			text = '',
			html = [];
			
		for(var i = 0, len = Math.min(ds.length, options.count); i < len; ++i){
			d = ds[i];
			d = d.replace('<span class="entry-content">', '').replace(/<\/span>$/i, '');
			text = d.replace(/href="\/([^"]*?)"/ig,'href="http://twitter.com/$1" target="_blank"');
			html.push(options.lineTpl.replace('{|$status|}',text));
		}
		html = html.join('');
		html = options.container.html.replace('{|$lines|}', html);
		//alert(html)
		con.innerHTML = html;
		//afterShow();
	}
	
	function send(userName){
		var url 		= 'http://twitter.com/'+userName,
		xpath			= "//ol[@id='timeline']//span[@class=\'entry-content\']";	
		con.innerHTML 	= 'loading...';
		yql_req_html(url, xpath, showTweets);		
	}
	
	setTimeout(function(){send(options.username)},0);	

})();
